package com.gem.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileUploadController {
    @Value("target")
    private String targetPath;
    @RequestMapping("/uploadPage")
    public  String uploadPage(){
        return "upload/fileupload";
    }
    //实现文件上传
    @RequestMapping("upload")
    public String upload(MultipartFile imgfile, Model model) throws IOException {
        String fileName="";
        System.out.println("target"+targetPath);
        fileName=imgfile.getOriginalFilename();//包含上传文件的后缀名
        //文件后缀
        String suffix= fileName.substring(fileName.lastIndexOf("."));
        System.out.println("文件后缀"+suffix);
   //文件重命名
    fileName= UUID.randomUUID().toString().replace("-","").toLowerCase()+suffix;
        System.out.println("文件"+fileName);
        //上传
        imgfile.transferTo(new File(targetPath,fileName));
        //模拟文件保存到数据库
      model.addAttribute("currimg",fileName);
        return "upload/show";
    }
}
